package com.itcast.java.product.service.impl;

import com.itcast.java.common.base.ServiceException;
import com.itcast.java.product.entity.PmsCategoryEntity;
import com.itcast.java.product.mapper.PmsCategoryMapper;
import com.itcast.java.product.service.IPmsCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itcast.java.product.vo.AddPmsCategoryVO;
import com.itcast.java.product.vo.UpdatePmsCategoryVO;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 商品三级分类服务实现类
 *
 * @author xiaobai
 * @date 2021-06-27 19:31:58
 */
@Service
public class PmsCategoryServiceImpl extends ServiceImpl<PmsCategoryMapper, PmsCategoryEntity> implements IPmsCategoryService {

    @Autowired
    private ModelMapper modelMapper;

    @Override
    public Boolean deleteByIds(List<String> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public void deleteById(String id) {
        int count = baseMapper.deleteById(id);
        if (count == 0) {
            throw new ServiceException("分类不存在！");
        }
    }

    @Override
    public Boolean update(UpdatePmsCategoryVO updatePmsCategoryVO) {
        PmsCategoryEntity pmsCategoryEntity = modelMapper.map(updatePmsCategoryVO, PmsCategoryEntity.class);
        return baseMapper.updateById(pmsCategoryEntity) > 0;
    }

    @Override
    public Boolean create(AddPmsCategoryVO addPmsCategoryVO) {
        PmsCategoryEntity pmsCategoryEntity = modelMapper.map(addPmsCategoryVO, PmsCategoryEntity.class);

        PmsCategoryEntity parentCategory = baseMapper.select(pmsCategoryEntity.getParentCid());
        if (parentCategory == null) {
            throw new ServiceException("父分类不存在！");
        }
        pmsCategoryEntity.setCatLevel(parentCategory.getCatLevel()+1);
        pmsCategoryEntity.setShowStatus(1);

        List<String> names = baseMapper.selectChildrenNameByParentCid(pmsCategoryEntity.getParentCid());
        if (names.contains(pmsCategoryEntity.getName())) {
            throw new ServiceException("已存在名称相同的分类！");
        }

        if (pmsCategoryEntity.getSort() == null) {
            pmsCategoryEntity.setSort(0);
        }

        return baseMapper.insert(pmsCategoryEntity) > 0;
    }
}
